package com.xcc.consumer.kafka;

import com.xcc.bean.Consumer;
import com.xcc.constant.CommonConstant;
import com.xcc.constant.Names;
import com.xcc.consumer.bean.Calllog;
import com.xcc.consumer.dao.HbaseDao;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;

import java.io.IOException;
import java.util.Arrays;
import java.util.Properties;

public class ConsumerAndHbaseProducer implements Consumer {

    private HbaseDao dao;

    public ConsumerAndHbaseProducer() {
        try {
            dao = new HbaseDao();
            dao.init();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void getHbaseTable(String tel, String startTime, String endTime) throws Exception {
        dao.getValue(tel, startTime, endTime);
    }

    @Override
    public void consumer() {
        //创建kafka消费者
        try {
            Properties pro = new Properties();
            pro.load(Thread.currentThread().getClass().getResourceAsStream("/kafka.properties"));
            KafkaConsumer<String, String> kafkaConsumer = new KafkaConsumer<String, String>(pro);
            kafkaConsumer.subscribe(Arrays.asList(Names.TOPIC.getValue()));
            while (true) {
                ConsumerRecords<String, String> consumerRecords = kafkaConsumer.poll(100);
                for (ConsumerRecord<String, String> record : consumerRecords) {
                    Calllog calllog = new Calllog(record.value());
                    //设置为主叫
                    calllog.setFlag(CommonConstant.FLAG_TURE);
                    calllog.setRowKey(dao.getRowkeyRegion(calllog.getCall1(), calllog.getCalltime(), CommonConstant.REGION_COUNT)
                            + "_" + calllog.getCall1() + "_" + calllog.getCalltime() + "_" + calllog.getCall2() + "_" + calllog.getDuration()+"_"+CommonConstant.FLAG_TURE);
                    dao.put(calllog);
                }
                Thread.sleep(500);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
